import 'package:flutter/material.dart';

class Demo extends StatefulWidget {
  const Demo({super.key});

  @override
  State<Demo> createState() => _DemoState();
}

class _DemoState extends State<Demo> {
  bool withTree = false; // 复选框选中状态
  Widget getAlertDialog(BuildContext context) {
    return AlertDialog(
      title: Text("提示"),
      content: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Text("您确定要删除当前文件吗?"),
          Row(
            children: [
              Text("同时删除子目录？"),
              Checkbox(
                value: withTree,
                onChanged: (bool? value) => setState(() {
                  withTree = !withTree;
                }),
              )
            ],
          )
        ],
      ),
      actions: <Widget>[
        TextButton(
          child: Text("取消"),
          onPressed: () => Navigator.of(context).pop(), // 关闭对话框
        ),
        TextButton(
          child: Text("删除"),
          onPressed: () {
            //关闭对话框并返回true
            Navigator.of(context).pop(true);
          },
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text("state改后，checkbox选中状态不会更新呢？"),
        Text("因为Dialog是一个新页面"),
        //点击该按钮后弹出对话框
        ElevatedButton(
          child: Text("AlertDialog"),
          onPressed: () async {
            //弹出对话框并等待其关闭
            bool? delete = await showDialog<bool>(
              context: context,
              builder: getAlertDialog,
            );
            if (delete == null) {
              print("取消删除");
            } else {
              print("已确认删除");
              //... 删除文件
            }
          },
        ),
      ],
    );
  }
}

void main(List<String> args) {
  runApp(MaterialApp(
    home: Scaffold(body: Demo()),
  ));
}
